package com.heima.behavior.service.impl;

import com.heima.behavior.entity.ApBehaviorEntry;
import com.heima.behavior.service.IApBehaviorEntryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * APP行为实体表,一个行为实体可能是用户或者设备，或者其它 服务实现类
 * </p>
 *
 * @author Wq
 * @since 2022-10-18
 */
@Service
public class ApBehaviorEntryServiceImpl implements IApBehaviorEntryService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public ApBehaviorEntry getEntryByUserId(Integer userId) {
        /*LambdaQueryWrapper<ApBehaviorEntry> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ApBehaviorEntry::getEntryId, userId);
        ApBehaviorEntry entry = this.getOne(wrapper);
        if (entry == null) {
            //新增
            entry = new ApBehaviorEntry();
            entry.setType(1);
            entry.setEntryId(userId.toString());
            entry.setCreatedTime(new Date());
            this.save(entry);
        }
        return entry;*/
        //先根据userId查询  查不到新增 返回entry对象
        Query query = new Query(Criteria.where("entryId").is(userId.toString()));
        ApBehaviorEntry entry = mongoTemplate.findOne(query, ApBehaviorEntry.class);
        if (entry == null) {
            //新增
            entry = new ApBehaviorEntry();
            entry.setType(1);
            entry.setEntryId(userId.toString());
            entry.setCreatedTime(new Date());
            mongoTemplate.save(entry);
        }
        return entry;
    }
}
